package cn.szzsi.service;

import cn.szzsi.common.model.CustomerDividend;
import cn.szzsi.common.model.Member;
import cn.szzsi.common.model.Orders;
import cn.szzsi.common.model.SiteConfig;
import cn.szzsi.core.kit.UtilDate;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务层(处理会员分红)
 * Created by zhengy on 2017/2/13.
 */
public class DividendService {
    public static final DividendService ds=new DividendService();


    //获取培养津贴列表
    public Map<String,Object> getDividendList(Integer dataLevel, String uid, String profitDate ){
        Map<String,Object> result = new HashMap<String,Object>();

        List<Record> lr = Db.find("select m.code,m.username,m.phone,b.*  from mall_member m right join mall_customer_dividend b on m.id=b.mid where b.dataLevel=? and b.profitDate=? and b.uid=?",dataLevel,profitDate,uid);
        result.put("data",lr);
        result.put("rewardNum",lr.size());//分红人数

        SiteConfig siteConfig= SiteConfig.dao.findByShopId(uid);
        Integer rewardPercent= siteConfig.getInt("rewardPercent"+dataLevel);
        result.put("rewardPercent",rewardPercent);//分红比例

        //获取所选当天的营业额(totalAmount)
        Orders orders=new Orders();
        String profitDateEnd=profitDateEnd(profitDate);//截止到分红当天凌晨加上24小时之后的时间
        orders=orders.findFirst("select sum(totalAmount) totalAmount from mall_orders where paymentStatus='2' and uid=? and createDate>? and createDate<=?",uid,profitDate,profitDateEnd);
        BigDecimal totalAmount=orders.getBigDecimal("totalAmount");
        if(totalAmount==null){
            totalAmount=new BigDecimal(0);
        }
        result.put("totalAmount",totalAmount);//近日营业额
        result.put("rewardCash",totalAmount.multiply(new BigDecimal(rewardPercent).divide(new BigDecimal(100))));//分红金额
        return result;
    }

    //根据dataLevel,profitDate,uid获取分红列表
    public void distribution(Integer dataLevel, String profitDate, String uid){
        List<CustomerDividend> lr = CustomerDividend.dao.find("select * from mall_customer_dividend b  where b.dataLevel=? and b.profitDate=? and b.uid=?",dataLevel,profitDate,uid);
        for(CustomerDividend dividend:lr){
            dividend.set("status",1).update();
        }
    }


    //生成培养津贴
    public void createProfit(String shopId, Integer dataLevel, String profitDate){
        SiteConfig siteConfig= SiteConfig.dao.findByShopId(shopId);
        //根据输入的级别来获取该级别需要直荐多少人及分销的比例
        Integer rewardPercent=siteConfig.getInt("rewardPercent"+dataLevel);//分销比例

        //获取所选当天的营业额(totalAmount)
        Orders orders=new Orders();
        String profitDateEnd=profitDateEnd(profitDate);//截止到分红当天凌晨加上24小时之后的时间
        orders=orders.findFirst("select sum(totalAmount) totalAmount from mall_orders where paymentStatus='2' and uid=? and createDate>? and createDate<=?",shopId,profitDate,profitDateEnd);
        BigDecimal totalAmount=orders.getBigDecimal("totalAmount");
        if(totalAmount==null){
            totalAmount=new BigDecimal(0);
        }

        //根据直荐人数查看那些会员符合条件
        String sqlplus="";
        sqlplus="total>="+siteConfig.getInt("rewardnum"+dataLevel)+"";
        /*if(dataLevel==6){
            sqlplus="total>="+siteConfig.getInt("rewardnum"+dataLevel)+"";
        }else{
            sqlplus="total>="+siteConfig.getInt("rewardnum"+dataLevel)+" and total<"+siteConfig.getInt("rewardnum"+(dataLevel+1));
        }*/

        BigDecimal mulRewardPercent=new BigDecimal(rewardPercent).divide(new BigDecimal(100));
        List<Member> list= Member.dao.find("select m.id, m.code,m.username,m.phone, p.* from(select pid ,count(*) as total,shopid from mall_member where shopId='"+shopId+"' and memberRankId='dafc86f6aee04a8aa9c722689ef65b3y' and pid!='0' group by pid having "+sqlplus+" )p left join mall_member m on p.pid=m.id order by p.total");
        System.out.println(list.size());
        for(Member member:list){
            String mid=member.getStr("id");//会员id
            Long rewardnum=member.getLong("total");//直荐正式会员人数
            BigDecimal profit=totalAmount.multiply(mulRewardPercent).divide(new BigDecimal(list.size()),2, BigDecimal.ROUND_HALF_DOWN);//分红金额
            CustomerDividend.saveInfo(mid,rewardnum,profit,0,dataLevel,shopId,profitDate);
        }
    }

    //获取分红当天凌晨加上24小时之后的时间
    public String profitDateEnd(String profitDate){
        Long strTime;//所选时间戳
        Long timeEnd;//24小时之后的时间戳
        String profitDateEnd="";//截止到分红当天凌晨加上24小时之后的时间
        try {
            strTime= UtilDate.strToTimestamp(profitDate);//获取分红日期的时间戳
            timeEnd=strTime+86400000;
            profitDateEnd= UtilDate.timestampToDateStr(timeEnd);//时间戳转换成日期字符串
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return profitDateEnd;
    }

}
